package com.guoguo.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.guoguo.base.PageBean;
import com.guoguo.base.TaskResource;
import com.guoguo.dao.ShortUrlMongoDao;
import com.guoguo.entity.Images;
import com.guoguo.entity.UserExt;
import com.guoguo.entity.UserOther;
import com.guoguo.entity.Users;
import com.guoguo.entity.vo.TaskInfoDayVO;
import com.guoguo.entity.vo.TaskInfoVO;
import com.guoguo.entity.vo.UserInfoVO;
import com.guoguo.entity.vo.UsersVO;
import com.guoguo.enums.AliOssImageEnum;
import com.guoguo.enums.RegexEnum;
import com.guoguo.mapper.ImagesMapper;
import com.guoguo.mapper.InviteRelationMapper;
import com.guoguo.mapper.PointFlowMapper;
import com.guoguo.mapper.UserExtMapper;
import com.guoguo.mapper.UserOtherMapper;
import com.guoguo.mapper.UsersMapper;
import com.guoguo.service.IUserExtService;
import com.guoguo.service.IUsersService;
import com.guoguo.service.UploadService;
import com.guoguo.utils.AliOssUtils;
import com.guoguo.utils.RedisUtils;
import com.guoguo.utils.StringUtils;
import com.guoguo.utils.UUIDUtils;
import com.guoguo.utils.aliOss.AliOssImageConfig;
import com.guoguo.utils.aliOss.AliOssImageConfigUtils;
import com.guoguo.utils.nowpay.DateHelper;

/**
 * Created by Administrator on 2017/8/7 0007.
 */
@Service
public class UsersServiceImpl implements IUsersService {
	// User接口
	@Autowired
	private UsersMapper usersMapper;

	// UserExtr接口
	@Autowired
	private UserExtMapper userExtMapper;

	@Autowired
	private InviteRelationMapper inviteRelationMapper;

	@Autowired
	private ImagesMapper imagesMapper;

	@Autowired
	private ApplicationContext applicationContext;

	@Autowired
	private ShortUrlMongoDao shortUrlMongoDao;

	@Autowired
	private UploadService uploadService;
	
	@Autowired
	private UserOtherMapper userOtherMapper;
	
	@Autowired
	private UserTaskInfoServiceImpl userTaskInfoServiceImpl;
	
	@Autowired
	private IUserExtService iUserExtService;
	
	@Autowired
	private PointFlowMapper pointFlowMapper;

	private String newuserpwd;

	@Override
	public Users findUsers(String userName, String nickName, String icon, int appId, int phoneType) {
		// 查询是否有第三方帐号存在
		Users users = null;
		String[] userNameArr = userName.split("_");
		if (userNameArr.length > 0) {
			Users temp = new Users();
			if ("qq".equals(userNameArr[0])) {
				temp.setQq(userName);
			} else if ("wx".equals(userNameArr[0])) {
				temp.setWebchat(userName);
			} else if ("wb".equals(userNameArr[0])) {
				temp.setWeibo(userName);
			} else {
				temp.setUsername(userName);
			}
			users = usersMapper.findAccount(temp);
		}
		// 如果没有第三方帐号存在，则创建一个新的帐号
		if (users == null) {
			users = new Users();
			users.setUserId(UUIDUtils.getUUID());
			users.setUsername(userName);
			users.setNickname(nickName);
			users.setAppId(appId);
			users.setPhoneType(phoneType);
			usersMapper.insertUsers(users);

			UserExt userExt = new UserExt();
			userExt.setUserId(users.getUserId());
			userExt.setIcon(icon);

			Date date = new Date();
			userExt.setCreateTime(date);
			userExt.setRegistered(date);
			userExt.setLastTime(date);

			userExtMapper.insertUserExt(userExt);
		}
		return users;
	}

	@Override
	public Users findUser(String userName, String userpwd) {
		Users users = new Users();
		users.setUsername(userName);
		users.setUserpwd(userpwd);
		Users user = usersMapper.findUserAccount(users);
		return user;
	}

	@Override
	public boolean findUsers(String userName, String userpwd) {
		Users user = findUser(userName, userpwd);
		if (user != null) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Users findUserById(String userId) {
		Users users = usersMapper.selectByPrimaryKey(userId);
		return users;
	}

	@Override
	public UsersVO findUsersInfo(String userId) {
		UsersVO usersVO = usersMapper.findUsersInfo(userId);
		return usersVO;
	}

	@Override
	public UserInfoVO findUsersInfoVO(String userId) {
		UserInfoVO userInfoVO = usersMapper.findUsersInfoVO(userId);
		if (userInfoVO.getIcon() != null && !StringUtils.relace(userInfoVO.getIcon(), RegexEnum.IS_NET_URL.getValue())) {
			// AliOssImageConfig aliOssImageConfig = new
			// AliOssImageConfig("test");
			userInfoVO.setIcon(AliOssUtils.getImageUrl(userInfoVO.getIcon()));// ,
																				// aliOssImageConfig));
		}
		return userInfoVO;
	}

	@Override
	public void updateUsersInfo(Users users, UserExt userExt) {
		if (users != null) {
			usersMapper.updateUsers(users);
		}
		if (userExt != null) {
			userExtMapper.updateUserExt(userExt);
		}
	}

	/**
	 * 用户注册
	 */
	@Override
	public boolean userRegister(String username, String userpwd, String icon, String nickname, String appId) {
		// 查看手机号码是否存在
		Users users = null;
		String[] usernames = username.split("");
		if (usernames.length > 0) {
			Users step = new Users();
			if ("phone".equals(usernames[0])) {
				users = usersMapper.findPhone(step);
			}
		}
		if (username == null) {
			users = new Users();
			UserExt userExt = new UserExt();
			users.setUsername(username);
			Date date = new Date();
			usersMapper.insertUsers(users);
		}
		return true;
	}

	/**
	 * 找回密码
	 *
	 * @param username
	 * @param userpwd
	 * @param phone
	 * @return
	 */
	@Override
	public boolean updateUserpwd(String username, String userpwd, String phone) {

		// 验证手机号是否正确

		if (StringUtils.isPhone("phone")) {
			if (phone.length() > 0) {
				Users user = new Users();
				user.setUserpwd(newuserpwd);
				usersMapper.insertUsers(user);
				return true;
			} else {
				return false;
			}
		}
		return false;

	}

	/**
	 * 查询所有用户
	 *
	 * @return
	 */
	@Override
	public PageBean<UsersVO> selectUserList(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		return new PageBean<UsersVO>(usersMapper.selectUserList());
	}

	@Override
	public int insertUsers(Users users) {
		return usersMapper.insertUsers(users);

	}

	@Override
	public int updateUsers(Users users) {
		return usersMapper.updateUsers(users);

	}

	@Override
	public Users selectByPrimaryKey(String userId) {
		return usersMapper.selectByPrimaryKey(userId);
	}

	@Override
	public int count(String phone) {
		return usersMapper.count(phone);

	}

	/**
	 * 游客登录
	 *
	 * @param Mac
	 * @return
	 */
	@Override
	public boolean guestLogin(String Mac) {
		if (Mac != null && "Mac".equals("Mac")) {
			RedisUtils redisUtils = RedisUtils.getInstance();
			redisUtils.set("Mac", Mac);
			return true;

		}
		return false;
	}

	/**
	 * @Description：查询注册的用户是否被邀请过
	 * @author: WYZ
	 * @since: 2017年10月25日 下午7:18:46
	 */
	@Override
	public String selectUserIsHaveSrcUser(String phone) {
		List<String> isHaveSrcUserList = new ArrayList<String>();
		String isHaveSrcUser = null;
		isHaveSrcUserList = inviteRelationMapper.selectUserIsHaveSrcUser(phone);
		if (isHaveSrcUserList.size() > 0 && isHaveSrcUserList != null) {
			isHaveSrcUser = isHaveSrcUserList.get(0);
		}
		return isHaveSrcUser;
	}

	/**
	 * @throws Exception
	 * @Description： 邀请有奖基本数据
	 * @author: WYZ
	 * @since: 2017年10月26日 下午8:28:29
	 */
	@Override
	public Map<String, String> invitationAwardBasic(String userId, String imgId) throws Exception {
		Map<String, String> data = new HashMap<String, String>();
		Integer inviteCount = null;
		Integer invitAllCount = null;
		RedisUtils redisUtils = RedisUtils.getInstance();
		// String waterImgUrl = null;
		Images images = new Images();
		// AliOssImageConfig aliOssImageConfig = new AliOssImageConfig("test");
		if (!StringUtils.isEmptyString(userId)) {
			Users users = usersMapper.selectByPrimaryKey(userId);
			if (users != null) {
				data.put("username", users.getNickname());// 用户名字
				//查询邀请人的所有邀请的人数
				invitAllCount = pointFlowMapper.selectInvitAllCount(userId);
				if(invitAllCount > 0){
					data.put("invitAcount", invitAllCount.toString());// 邀请人数
					data.put("awardAcount", invitAllCount*1000 + "");// 累计获得的金币奖励
				}else{
					data.put("invitAcount", "0");// 邀请人数
					data.put("awardAcount", "0");// 累计获得的金币奖励
				}
			}
			UserExt userExt = userExtMapper.findUserExt(userId);
			if (userExt != null) {
				data.put("icon", AliOssUtils.getImageUrl(userExt.getIcon()));// ,
																				// aliOssImageConfig));//用户头像url
				// data.put("icon", userExt.getIcon());
			}
		}
		// 查询图片
		if (!StringUtils.isEmptyString(imgId)) {
			images = imagesMapper.selectByPrimaryKey(imgId);
		} else {
			images = imagesMapper.selectByPrimaryKey("62BBFAA584964F0E8F3AE9A74F19DFB1");
		}

		int num = imagesMapper.countByAlbId(images.getAlbId());
		String str = num == 0 ? "" : "(" + num + "P)";
		if (!StringUtils.isEmptyString(imgId)) {
			images = imagesMapper.selectByPrimaryKey(imgId);
			if (images != null) {
				data.put("imgDescription", images.getImgDescription());// 图片描述

				data.put("imgDescriptionInvariant", "扫码查看全套" + str);// 图片不变描述
				data.put("originalUrl", AliOssUtils.getImageUrl(images.getOriginalUrl()));// ,
																							// aliOssImageConfig));//图片url
			}
		} else {
			images = imagesMapper.selectByPrimaryKey("62BBFAA584964F0E8F3AE9A74F19DFB1");
			if (images != null) {
				data.put("imgDescription", images.getImgDescription());// 图片描述
				data.put("imgDescriptionInvariant", "扫码查看全套" + str);// 图片不变描述
				data.put("originalUrl", AliOssUtils.getImageUrl(images.getOriginalUrl()));// ,
																							// aliOssImageConfig));//图片url
			}
		}
		inviteCount = inviteRelationMapper.selectAllInviteRelation(userId,new Date());
		if(inviteCount > 0){
			if (!redisUtils.hexists(TaskResource.REDIS_DAY_FLAG_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString())) {
				redisUtils.hset(TaskResource.REDIS_DAY_FLAG_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString(), inviteCount.toString());
				redisUtils.expire(TaskResource.REDIS_DAY_FLAG_STATUS + userId, DateHelper.getTodayLastTime());
			}else{
				redisUtils.hset(TaskResource.REDIS_DAY_FLAG_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString(), inviteCount.toString());
				redisUtils.expire(TaskResource.REDIS_DAY_FLAG_STATUS + userId, DateHelper.getTodayLastTime());
			}
		}
		return data;
	}

	/**
	 * @throws Exception
	 * @Description： 邀请有奖二维码数据
	 * @author: WYZ
	 * @since: 2017年10月26日 下午8:28:29
	 */
	@Override
	public Map<String, String> invitationAwardQR(String userId, String imgId) throws Exception {
		Map<String, String> data = new HashMap<String, String>();
		String uploadQR = null;
		String albId = null;
		Images images = new Images();
		// AliOssImageConfig aliOssImageConfig = new AliOssImageConfig("test");
		if (!StringUtils.isEmptyString(imgId)) {
			images = imagesMapper.selectByPrimaryKey(imgId);
			if (images != null) {
				albId = images.getAlbId();
			}
		} else {
			images = imagesMapper.selectByPrimaryKey("62BBFAA584964F0E8F3AE9A74F19DFB1");
			if (images != null) {
				albId = images.getAlbId();
			}
		}
		if (!StringUtils.isEmptyString(userId)) {
			uploadQR = uploadService.uploadQRCode(userId, albId);
			// data.put("uploadQR", uploadQR);//二维码
			data.put("uploadQR", AliOssUtils.getImageUrl(uploadQR));// ,
																	// aliOssImageConfig));//二维码
		}
		int num = imagesMapper.countByAlbId(albId);
		// TODO: 2017/10/31 0031 二维码样式
		AliOssImageConfig aliOssImageConfigN = AliOssImageConfigUtils.getWaterMark(uploadQR, "扫码查看全套(" + num + "P)", AliOssImageEnum.ALI_HANDLE_TEXT_DROIDSANSFALLBACK.getValue());
		// TODO: 2017/10/31 0031 压缩样式
		// AliOssImageConfig aliOssImageConfign =
		// AliOssImageConfigUtils.getResize(70, 0, 0, 0);
		// AliOssImage abstractAliOssImage =
		// AliOssImageFactory.createAliOssImage(aliOssImageConfigN);
		// abstractAliOssImage.operatingString(aliOssImageConfigN);
		// List<AliOssImageConfig> aliOssImageConfigs = new ArrayList<>();
		// aliOssImageConfigs.add(aliOssImageConfign);
		// aliOssImageConfigs.add(aliOssImageConfigN);
		// List<String> urlList = new ArrayList<>();
		// urlList.add(images.getOriginalUrl());

		String waterImgUrl = AliOssUtils.imageProcess(images.getOriginalUrl(), aliOssImageConfigN);
		data.put("waterImgUrl", waterImgUrl);
		return data;
	}

	/**
	 * @Description： 用户设置
	 * @author: WYZ
	 * @since: 2017年11月6日 下午1:45:46
	 */
	@Override
	public Map<String, String> userSet(String userId) {
		Map<String, String> data = new HashMap<String, String>();
		Users users = new Users();
		if (!StringUtils.isEmpty(userId) && !userId.equals("") && !userId.equals("null")) {
			users = usersMapper.selectByPrimaryKey(userId);
			if (users != null) {
				data.put("status", "200");// 用户存在
				if (!StringUtils.isEmpty(users.getPhone()) && !users.getPhone().equals("")) {
					data.put("phone", users.getPhone());
					//data.put("phoneUrl", PropertyUtils.getProperty("api.properties", "api.domainName") + "api/bindingSuccess/");
				} else {
					data.put("phone", "未绑定");
					//data.put("phoneUrl", PropertyUtils.getProperty("api.properties", "api.domainName") + "api/noBinding/");
				}
				if (!StringUtils.isEmpty(users.getQq())) {
					data.put("QQ", users.getQq());
				} else {
					data.put("QQ", "未绑定");
				}
				if (!StringUtils.isEmpty(users.getWebchat())) {
					data.put("webchat", users.getWebchat());
				} else {
					data.put("webchat", "未绑定");
				}
				if (!StringUtils.isEmpty(users.getWeibo())) {
					data.put("weibo", users.getWeibo());
				} else {
					data.put("weibo", "未绑定");
				}
			} else {
				data.put("status", "210");// 用户不存在
			}

		} else {
			data.put("status", "207");// userId为空
		}
		return data;
	}

	/**  
	 * @Description： 查询手机用户是否存在
	 * @author: WYZ 
	 * @since: 2017年11月6日 下午4:58:05  
	 */
	@Override
	public Integer selectCountByPhone(String phoneNo) {
		Integer phoneCount = null;
		phoneCount = usersMapper.selectCountByPhone(phoneNo);
		return phoneCount;
	}

	/**  
	 * @Description： 绑定用户手机号
	 * @author: WYZ 
	 * @since: 2017年11月7日 上午11:08:47  
	 */
	@Override
	public boolean bingPhone(String userId, String phone) {
		Integer userCount = null;
		Integer userExCount = null;
		Integer addCount = null;
		String isScrUser = null;
		boolean isSuccess = false;
		userCount = usersMapper.updatePhone(userId,phone);
		userExCount = userExtMapper.updatePhone(userId,phone,new Date());
		//查询绑定的用户是否被邀请过,当天邀请人次数小于10次
		isScrUser = selectUserIsHaveSrcUser(phone);
		if (!StringUtils.isEmpty(isScrUser) && !isScrUser.equals("") && !isScrUser.equals("null")) {
            //userExt.setPoint(1000L);
            addCount = iUserExtService.addSrcUserPoint(isScrUser,phone);
		}    
		if(userCount > 0 && userExCount > 0 && addCount > 0){
			isSuccess = true;
		}
		return isSuccess;
	}
    
	/**  
	 * @Description： 设置密码
	 * @author: WYZ 
	 * @since: 2017年11月7日 上午11:08:47  
	 */
	@Override
	public boolean setPassword(String userId, String password) {
		boolean isSuccess = false;
		isSuccess = usersMapper.setPassword(userId,password);
		return isSuccess;
	}
    
	/**  
	 * @Description： 重置密码验证
	 * @author: WYZ 
	 * @since: 2017年11月7日 上午11:08:47  
	 */
	@Override
	public boolean resetPassword(String userId, String phone) {
		Integer isSuccessCount = null;
		boolean isSuccess = false;
		isSuccessCount = usersMapper.resetPassword(userId,phone);
		if(isSuccessCount > 0){
			isSuccess = true;
		}
		return isSuccess;
	}

	/**  
	 * @Description： 插入用户经验表
	 * @author: WYZ 
	 * @since: 2017年11月10日 上午10:58:11  
	 */
	@Override
	public int insertUserOther(UserOther userOther) {
		return userOtherMapper.insert(userOther);
	}
    
	/**  
	 * @Description：查询用户邀请和礼包的标记
	 * @author: WYZ 
	 * @since: 2017年11月16日 上午10:58:11  
	 */
	@SuppressWarnings("unchecked")
	@Override
	public UserInfoVO findInvitGiftFlag(String userId) {
		UserInfoVO userInfoVO = new UserInfoVO();
		Integer inviteCount = null;
		String giftFlag = "0";//0是无红点,1是有红点
		String invitFlag = null;
		RedisUtils redisUtils = RedisUtils.getInstance();
		List<TaskInfoVO> weekTaskList = new ArrayList<>();
		List<TaskInfoDayVO> dayTaskList = new ArrayList<>();
		Map<String, Object> data = new HashMap<String, Object>();
		//查询礼物的状态值
		data = userTaskInfoServiceImpl.giftCentre(userId);
		Integer weekTaskCount = null;
		weekTaskList = (List<TaskInfoVO>) data.get("weekTaskList");
		dayTaskList = (List<TaskInfoDayVO>) data.get("dayTaskList");
		for (TaskInfoVO taskInfoVO : weekTaskList) {
			if(taskInfoVO.getCurrentStatus().equals(1)){
				giftFlag = "1";
				break;
			}
		}
		if(!giftFlag.equals("1")){
			for (TaskInfoDayVO taskInfoDayVO : dayTaskList) {
				if(taskInfoDayVO.getCurrentStatus().equals(1)){
					giftFlag = "1";
					break;
				}
			}
		}
		//查询邀请的状态值,查询邀请人当下所有被邀请人是否当天注册或绑定
		inviteCount = inviteRelationMapper.selectAllInviteRelation(userId,new Date());
		if(inviteCount > 0){
			if (!redisUtils.hexists(TaskResource.REDIS_DAY_FLAG_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString())) {
				invitFlag = "1";
			}else{
				weekTaskCount = Integer.valueOf(redisUtils.hget(TaskResource.REDIS_DAY_FLAG_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString()));
				redisUtils.expire(TaskResource.REDIS_DAY_FLAG_STATUS + userId, DateHelper.getTodayLastTime());
				if(inviteCount > weekTaskCount){
					invitFlag = "1";
				}else{
					invitFlag = "0";
				}
			}
		}else{
			invitFlag = "0";
		}
		userInfoVO.setInvitFlag(invitFlag);
		userInfoVO.setGiftFlag(giftFlag);
		return userInfoVO;
	}

}
